package com.ang.juc.n4.t1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Test2_1 {
    private static final Logger log = LoggerFactory.getLogger(Test2_1.class);
    private final ReentrantLock lock = new ReentrantLock();

    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();

    public Runnable getRunTask1() {
        return () -> {
                while (true){
                    System.out.println(Thread.currentThread().getName() + "   获取锁" + lock.hashCode() + ":" + lock.isLocked());
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + "   得到锁" + lock.hashCode() + ":" + lock.isLocked());
                    c2.signal();
                    try {
                        System.out.println(Thread.currentThread().getName() + "   释放锁，并等待唤醒");
                        c1.await();
                        System.out.println(Thread.currentThread().getName() + " 被唤醒，开始工作");
                        Thread.sleep(3000);
                        System.out.println(Thread.currentThread().getName() + "   工作结束");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    } finally {
                        lock.unlock();
                    }
                }
        };
    }

    public Runnable getRunTask2() {
        return () -> {
            while (true) {
                System.out.println(Thread.currentThread().getName() + "   获取锁" + lock.hashCode() + ":" + lock.isLocked());
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "   得到锁" + lock.hashCode() + ":" + lock.isLocked());
                c1.signal();
                try {
                    System.out.println(Thread.currentThread().getName() + "   释放锁，并等待唤醒");
                    c2.await();
                    System.out.println(Thread.currentThread().getName() + " 被唤醒，开始工作");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + "   工作结束");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        };
    }

    public void test1() throws Exception {
        new Thread(getRunTask1(), "线程1").start();
        Thread.sleep(500);
        new Thread(getRunTask2(), "线程2").start();
    }

    //=====================================
    public static void main(String[] args) throws Exception {
        System.out.println("rice-----------------------");
        Test2_1 test21 = new Test2_1();
        test21.test1();
    }

}
